package com.example.spring.multi.communication.socket;

import com.alibaba.fastjson.JSONObject;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Surging
 * @version 1.0
 * @ClassName SocketStorageDeal
 * @date 2022-06-17 15:08
 * @desc Socket存储处理类
 */
@Slf4j
@Component
public class SocketStorageDeal {

    public static ConcurrentHashMap<String, NetSocket> socketMap = new ConcurrentHashMap<>();


    /**
     * @author Surging
     * @Description 记录所有的Socket连接通道
     * @param key 车场ID+socket ID  :  netSocket.writeHandlerID() + parkid + parkkey
     * @param netSocket 通道信息
     * @Return void       
     * @date 17:49 2022-06-17
     **/
   public static void addNetSocket(String key, NetSocket netSocket){
       socketMap.put(key, netSocket);
       log.info("添加socket[{}]成功!" + "剩余socket通道：" + socketMap.size() ,key);
   }

    /**
     * @param keyId  NetSocket ID
     * @author Surging
     * @Description
     * @Return void
     * @date 20:18 2022-09-05
     **/
    public static void removeNetSocket(String keyId){
        socketMap.remove(keyId);
        log.info("关闭socket[{}]成功!" + "剩余socket通道：" + socketMap.size() ,keyId);
    }

    /**
     * @param netSocket socket 通道
     * @param baseSocketResponse 传输的数据
     * @author Surging
     * @Description
     * @Return void
     * @date 16:11 2022-09-07
     **/
    public static void sendResponse(NetSocket netSocket, Object baseSocketResponse) {
        String message = JSONObject.toJSONString(baseSocketResponse);
        netSocket.write(message);
    }

    /**
     * @param parkId 车场code
     * @param message 消息实体
     * @author Surging
     * @Description 根据通道
     * @Return void
     * @date 16:13 2022-09-07
     **/
    public static void sendMessage(String parkId, Object message) {
        //关闭中控
        for (String strKey : SocketStorageDeal.socketMap.keySet()) {
            if (strKey.contains(parkId)) {
                NetSocket netSocket = socketMap.get(strKey);
                // 向通道发送消息
                sendResponse(netSocket, message);
                log.info("向通道strKey发送消息" + message.toString());
            }
        }
    }
}
